<template>
  <div class="log-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>操作日志</span>
          <div>
            <el-button type="primary" @click="handleExport">导出日志</el-button>
            <el-button type="danger" @click="handleClear" v-permission="'delete:log'">清理日志</el-button>
          </div>
        </div>
      </template>
      
      <div class="tab-container">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="管理员日志" name="admin">
            <div class="search-box">
              <el-form :inline="true" :model="queryParams" class="demo-form-inline">
                <el-form-item label="管理员">
                  <el-input v-model="queryParams.username" placeholder="请输入管理员账号" clearable />
                </el-form-item>
                <el-form-item label="操作类型">
                  <el-select v-model="queryParams.action" placeholder="请选择操作类型" clearable>
                    <el-option label="登录" value="login" />
                    <el-option label="创建" value="create" />
                    <el-option label="更新" value="update" />
                    <el-option label="删除" value="delete" />
                    <el-option label="其他" value="other" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    @change="handleDateChange"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleQuery">查询</el-button>
                  <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <el-table v-loading="loading" :data="logList">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="admin.username" label="管理员" width="120" />
              <el-table-column prop="action" label="操作类型" width="100">
                <template #default="scope">
                  <el-tag :type="getActionTagType(scope.row.action)">
                    {{ getActionName(scope.row.action) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="ip" label="IP地址" width="140" />
              <el-table-column prop="action" label="操作模块" width="120" />
              <el-table-column prop="details" label="操作内容" show-overflow-tooltip />
              <el-table-column prop="create_time" label="操作时间" width="180" />
            </el-table>
          </el-tab-pane>
          
          <el-tab-pane label="用户日志" name="user">
            <div class="search-box">
              <el-form :inline="true" :model="queryParams" class="demo-form-inline">
                <el-form-item label="用户账号">
                  <el-input v-model="queryParams.username" placeholder="请输入用户账号" clearable />
                </el-form-item>
                <el-form-item label="操作类型">
                  <el-select v-model="queryParams.action" placeholder="请选择操作类型" clearable>
                    <el-option label="登录" value="login" />
                    <el-option label="注册" value="register" />
                    <el-option label="支付" value="payment" />
                    <el-option label="学习" value="study" />
                    <el-option label="其他" value="other" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    @change="handleDateChange"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleQuery">查询</el-button>
                  <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <el-table v-loading="loading" :data="logList">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="username" label="用户账号" width="120" />
              <el-table-column prop="action" label="操作类型" width="100">
                <template #default="scope">
                  <el-tag :type="getActionTagType(scope.row.action)">
                    {{ getActionName(scope.row.action) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="ip" label="IP地址" width="140" />
              <el-table-column prop="user_agent" label="设备信息" width="140" show-overflow-tooltip />
              <el-table-column prop="content" label="操作内容" show-overflow-tooltip />
              <el-table-column prop="created_at" label="操作时间" width="180" />
            </el-table>
          </el-tab-pane>
          
          <el-tab-pane label="系统日志" name="system">
            <div class="search-box">
              <el-form :inline="true" :model="queryParams" class="demo-form-inline">
                <el-form-item label="日志级别">
                  <el-select v-model="queryParams.level" placeholder="请选择日志级别" clearable>
                    <el-option label="INFO" value="info" />
                    <el-option label="WARNING" value="warning" />
                    <el-option label="ERROR" value="error" />
                    <el-option label="CRITICAL" value="critical" />
                  </el-select>
                </el-form-item>
                <el-form-item label="模块">
                  <el-input v-model="queryParams.module" placeholder="请输入模块名称" clearable />
                </el-form-item>
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    @change="handleDateChange"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleQuery">查询</el-button>
                  <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <el-table v-loading="loading" :data="logList">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="level" label="级别" width="100">
                <template #default="scope">
                  <el-tag :type="getLevelTagType(scope.row.level)">
                    {{ scope.row.level && scope.row.level.toUpperCase() }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="module" label="模块" width="120" />
              <el-table-column prop="message" label="日志内容" show-overflow-tooltip />
              <el-table-column prop="created_at" label="记录时间" width="180" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="queryParams.page"
          :page-size="queryParams.limit"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 清理日志弹窗 -->
    <el-dialog title="清理日志" v-model="clearDialogVisible" width="400px">
      <el-form :model="clearForm" label-width="100px">
        <el-form-item label="日志类型">
          <el-select v-model="clearForm.type" placeholder="请选择日志类型">
            <el-option label="管理员日志" value="admin" />
            <el-option label="用户日志" value="user" />
            <el-option label="系统日志" value="system" />
            <el-option label="所有日志" value="all" />
          </el-select>
        </el-form-item>
        <el-form-item label="保留天数">
          <el-input-number v-model="clearForm.days" :min="1" :max="365" />
          <span class="tip-text">天以前的日志将被删除</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clearDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmClear" v-permission="'delete:log'">确认清理</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminLogs, getUserLogs, getSystemLogs, clearLogs, exportLogs } from '@/api/logs'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const activeTab = ref('admin')
const loading = ref(false)
const logList = ref([])
const total = ref(0)
const dateRange = ref([])
const clearDialogVisible = ref(false)

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  username: '',
  action: '',
  level: '',
  module: '',
  start_date: '',
  end_date: ''
})

// 清理日志表单
const clearForm = reactive({
  type: 'admin',
  days: 30
})

// 监听标签页变化，重置查询参数
watch(activeTab, () => {
  resetQuery()
})

// 获取日志列表
const getList = async () => {
  loading.value = true
  try {
    let res
    
    if (activeTab.value === 'admin') {
      res = await getAdminLogs(queryParams)
    } else if (activeTab.value === 'user') {
      res = await getUserLogs(queryParams)
    } else if (activeTab.value === 'system') {
      res = await getSystemLogs(queryParams)
    }
    
    if (res && res.code === 0) {
      logList.value = res.data.items
      total.value = res.data.total
    } else {
      ElMessage.error(res?.message || '获取日志列表失败')
    }
  } catch (error) {
    console.error('获取日志列表失败', error)
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.username = ''
  queryParams.action = ''
  queryParams.level = ''
  queryParams.module = ''
  queryParams.start_date = ''
  queryParams.end_date = ''
  dateRange.value = []
  handleQuery()
}

// 日期范围变化
const handleDateChange = (val) => {
  if (val) {
    queryParams.start_date = val[0]
    queryParams.end_date = val[1]
  } else {
    queryParams.start_date = ''
    queryParams.end_date = ''
  }
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 每页条数改变
const handleSizeChange = (val) => {
  queryParams.limit = val
  queryParams.page = 1
  getList()
}

// 标签页切换
const handleTabChange = () => {
  resetQuery()
}

// 导出日志
const handleExport = async () => {
  try {
    const params = {
      type: activeTab.value,
      ...queryParams
    }
    const res = await exportLogs(params)
    
    // 创建下载链接
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `${activeTab.value}_logs_${new Date().getTime()}.xlsx`
    link.click()
    URL.revokeObjectURL(link.href)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出日志失败', error)
    ElMessage.error('导出日志失败')
  }
}

// 打开清理日志弹窗
const handleClear = () => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission('delete:log')) {
    ElMessage.warning('测试账号不能清理日志')
    return
  }
  
  clearForm.type = activeTab.value
  clearDialogVisible.value = true
}

// 确认清理日志
const confirmClear = async () => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission('delete:log')) {
    ElMessage.warning('测试账号不能清理日志')
    return
  }

  ElMessageBox.confirm(`确认要清理${clearForm.days}天前的${getLogTypeName(clearForm.type)}吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await clearLogs(clearForm.type, clearForm.days)
      if (res.code === 0) {
        ElMessage.success('清理成功')
        clearDialogVisible.value = false
        getList()
      } else {
        ElMessage.error(res.message || '清理失败')
      }
    } catch (error) {
      console.error('清理日志失败', error)
      ElMessage.error('清理日志失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 获取日志类型名称
const getLogTypeName = (type) => {
  const typeMap = {
    'admin': '管理员日志',
    'user': '用户日志',
    'system': '系统日志',
    'all': '所有日志'
  }
  return typeMap[type] || '日志'
}

// 获取操作类型名称
const getActionName = (action) => {
  const adminActionMap = {
    'login': '登录',
    'create': '创建',
    'update': '更新',
    'delete': '删除',
    'other': '其他'
  }
  
  const userActionMap = {
    'login': '登录',
    'register': '注册',
    'payment': '支付',
    'study': '学习',
    'other': '其他'
  }
  
  if (activeTab.value === 'admin') {
    return adminActionMap[action] || action
  } else {
    return userActionMap[action] || action
  }
}

// 获取操作类型标签样式
const getActionTagType = (action) => {
  const typeMap = {
    'login': 'success',
    'register': 'info',
    'create': 'primary',
    'update': 'warning',
    'delete': 'danger',
    'payment': 'success',
    'study': 'info',
    'other': ''
  }
  return typeMap[action] || ''
}

// 获取日志级别标签样式
const getLevelTagType = (level) => {
  if (!level) return ''
  const typeMap = {
    'info': 'info',
    'warning': 'warning',
    'error': 'danger',
    'critical': 'danger'
  }
  return typeMap[level.toLowerCase()] || ''
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.log-list-container {
  height: 100%;
  padding: 20px;
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 20px;
  background: #f9fafc;
  padding: 16px;
  border-radius: 8px;
}

.el-table {
  flex: 1;
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 表格内容样式优化 */
:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .cell) {
  line-height: 1.5;
}

/* 标签样式 */
.el-tag {
  font-weight: 500;
}

/* 日志详情弹窗样式 */
.log-detail-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.log-detail-item {
  margin-bottom: 16px;
}

.log-detail-label {
  font-weight: bold;
  margin-bottom: 8px;
  color: #606266;
}

.log-detail-value {
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
  word-break: break-all;
  font-family: monospace;
  font-size: 13px;
}
</style> 